#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <QMessageBox>
#include "myprotocol.h"
#include <cstring>
#include <QIcon>
#include <QBoxLayout>
#include <QFile>
#include <QIODevice>
#include <cstdio>
#include <QDir>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    this->setFixedSize(this->size().width(),this->size().height());
    create_obj();

    this->setWindowIcon(QIcon(":/new/prefix1/Image/mesage.png"));
    this->setWindowTitle("MAIN MENU");

    QPalette qp = this->palette(); //重新拷贝一份和本对象palette相同的palette
    qp.setBrush(QPalette::Window,QBrush(QImage(":/new/prefix1/Image/Frame.jpg").scaled(this->size())));
    this->setPalette(qp);

    this->ui->connect_btn->setIcon(QIcon(":/new/prefix1/Image/Start.png"));
    this->ui->connect_btn->setIconSize(QSize(this->ui->connect_btn->size().width(),
                                             this->ui->connect_btn->size().height()));
    this->ui->pic->setPixmap(QPixmap(":/new/prefix1/Image/LuffyQ.png"));

    this->myhr->hide();
    this->mymanager->hide();
    this->myquery->hide();
    this->myadd->hide();
    this->myregister->hide();
    this->ui->login_btn->setEnabled(false);

    connect_signals_slots();

    this->myhr->set_socket(socket);
    this->myadd->set_socket(socket);
    this->myquery->set_socket(socket);
    this->staff_all_info->set_socket(socket);
    this->mymanager->set_socket(socket);

    this->ui->login_btn->setShortcut(Qt::Key_Return);

    this->ui->ip_line->setReadOnly(true);
    this->ui->port_line->setReadOnly(true);
}

Widget::~Widget()
{
    this->socket->close();
    delete ui;
}

void Widget::connect_signals_slots()
{
    //缺省信号
    connect(this->socket, &QTcpSocket::connected, [=](){
        this->ui->login_btn->setEnabled(true);
        this->ui->connect_btn->setEnabled(false);
        QMessageBox::information(this,"successful","连接成功");
    });
    connect(this->socket, &QTcpSocket::disconnected, [=](){
        this->ui->login_btn->setEnabled(false);
        this->ui->connect_btn->setEnabled(true);
        this->socket->close();//重要!!!!!!!!!!
    });
    connect(this->socket, &QTcpSocket::readyRead,[=](){
        QByteArray data_all = socket->readAll();
        char choose_s[5] = {0};
        int choose;
        memcpy(choose_s,data_all.data(),sizeof(choose_s));
        choose = atoi(choose_s);
        char recv_info[512] = {0};
        memcpy(recv_info,data_all.data() + 2,sizeof(recv_info));
        switch (choose)
        {
        case hrlogin_verify_protocol:
            if(!strcmp(recv_info,"yes"))
            {
                this->hide();
                this->myhr->show();
                QString success_str = "login successful!";
                QMessageBox::information(this->myhr,"successful",success_str);
                this->ui->account_line->clear();
                this->ui->password_line->clear();
            }
            else
            {
                QString error_str = "password wrong!";
                QMessageBox::critical(this,"error",error_str);
            }
            break;
        case add_verify_protocol:
            if(!strcmp(recv_info,"ok"))
            {
                QString success_str = "add successful!";
                QMessageBox::information(this->myadd,"successful",success_str);
            }
            else
            {
                QMessageBox::critical(this->myadd,"error","add error");
            }
            break;
        case search_verify_protocol:
            if(!strcmp(recv_info,"no"))
            {
                QString error_str = "search failure!";
                QMessageBox::critical(this->myhr,"error",error_str);
            }
            else
            {
                search_info_t mysearch_info;
                memcpy(&mysearch_info.staff_info,recv_info,sizeof(mysearch_info.staff_info));
                QStringList strlist;
                strlist.push_back(QString(mysearch_info.staff_info.name));
                strlist.push_back(QString::number(mysearch_info.staff_info.old));
                strlist.push_back(QString(mysearch_info.staff_info.department));
                strlist.push_back(QString::number(mysearch_info.staff_info.salary));
                emit this->myquery->myquery_signal(strlist,false);
                this->myhr->hide();
                this->myquery->show();
                this->myhr->my_clear_text_signal();
            }
            break;
        case modify_verify_protocol:
            if(!strcmp(recv_info,"ok"))
            {
                QMessageBox::information(this->myquery,"successful","modify successful");
            }
            else
            {
                QMessageBox::critical(this->myquery,"error","modify error");
            }
            break;
        case delete_verify_protocol:
            if(!strcmp(recv_info,"ok"))
            {
                QMessageBox::information(this->myquery,"successful","delete successful");
            }
            else
            {
                QMessageBox::critical(this->myquery,"error","delete error");
            }
            break;
        case select_all_verify_protocol:
            this->myhr->hide();
            this->staff_all_info->show();
            {
                QStringList strlist = QString(recv_info).split(" ");
                emit staff_all_info->my_select_signal(strlist);
            }
            break;
        case managerlogin_verify_protocol:
            if(!strcmp(recv_info,"yes"))
            {
                this->hide();
                this->mymanager->show();
                QString success_str = "login successful!";
                QMessageBox::information(this->mymanager,"successful",success_str);
                this->ui->account_line->clear();
                this->ui->password_line->clear();
            }
            else
            {
                QString error_str = "password wrong!";
                QMessageBox::critical(this,"error",error_str);
            }
            break;
        case register_verify_protocol:
            if(!strcmp(recv_info,"ok"))
            {
                emit this->mymanager->my_register_signal(true);
            }
            else
            {
                emit this->mymanager->my_register_signal(false);
            }
            break;
        case delete_usr_verify_protocl:
            if(!strcmp(recv_info,"ok"))
            {
                emit this->mymanager->my_delete_signal(true);
            }
            else
            {
                emit this->mymanager->my_delete_signal(false);
            }
            break;
        case managerquery_verify_protocol:
            if(!strcmp(recv_info,"no"))
            {
                QString error_str = "search failure!";
                QMessageBox::critical(this->mymanager,"error",error_str);
            }
            else
            {
                search_info_t mysearch_info;
                memcpy(&mysearch_info.staff_info,recv_info,sizeof(mysearch_info.staff_info));
                QStringList strlist;
                strlist.push_back(QString(mysearch_info.staff_info.name));
                strlist.push_back(QString::number(mysearch_info.staff_info.old));
                strlist.push_back(QString(mysearch_info.staff_info.department));
                strlist.push_back(QString::number(mysearch_info.staff_info.salary));
                emit this->myquery->myquery_signal(strlist,true);
                this->mymanager->hide();
                this->myquery->show();

                this->mymanager->my_clear_text_signal();
            }
            break;
        case select_allusr_verify_protocol:
            this->mymanager->hide();
            { //否则无法定义对象
                QStringList strlist = QString(recv_info).split(" ");
                emit this->mymanager->my_select_allusrs_signal(strlist);
            }
            break;
        default:
            break;
        }
    });

    //连接失败
    connect(this->socket, QOverload<QAbstractSocket::SocketError>::of(&QTcpSocket::error),
            [=](QAbstractSocket::SocketError socketError){
        QString error_str = QString::number(socketError);
        error_str += "(error_num),error_info:";
        error_str += socket->errorString();
        QMessageBox::critical(this, "error", error_str);
    });
    //我的信号
    connect(this->myhr,&HR::my_add_signal,[=](){
        this->myhr->hide();
        this->myadd->my_add_signal(false);
    });
    connect(this->mymanager,&ManagerOP::my_add_signal,[=](){
        this->mymanager->hide();
        this->myadd->my_add_signal(true);
    });
    connect(this->mymanager,&ManagerOP::my_select_staff_signal,[=](){
        this->mymanager->hide();
        QString mydata = QString::number(select_all_request_protocol);
        mydata += "no message";
        this->socket->write(mydata.toUtf8());
    });
    //返回信号
    connect(this->myhr,&HR::my_back_to_widget_signal,[=](){
        this->show();
    });
    connect(this->myadd,&Add::my_back_to_hrORmanagerop_signal,[=](){
        if(this->ui->root_check->isChecked())
        {
            this->mymanager->show();
        }
        else
        {
            this->myhr->show();
        }
    });
    connect(this->myquery,&Query::my_back_to_hrORmanagerop_signal,[=](){
        if(this->ui->root_check->isChecked())
        {
            this->mymanager->show();
        }
        else
        {
            this->myhr->show();
        }
    });
    connect(this->staff_all_info,&SelectStaff::my_back_to_hrORmanagerop_signal,[=](){
        if(this->ui->root_check->isChecked())
        {
            this->mymanager->show();
        }
        else
        {
            this->myhr->show();
        }
    });
    connect(this->mymanager,&ManagerOP::my_back_to_widget_signal,[=](){
        this->show();
    });
}

void Widget::create_obj()
{
    this->socket = new QTcpSocket(this);
    this->socket->setProxy(QNetworkProxy::NoProxy);
    this->myhr = new HR(this);
    this->myhr->setWindowFlag(Qt::Window);
    this->mymanager = new ManagerOP(this);
    this->mymanager->setWindowFlag(Qt::Window);
    this->myquery = new Query(this);
    this->myquery->setWindowFlag(Qt::Window);
    this->myadd = new Add(this);
    this->myadd->setWindowFlag(Qt::Window);
    this->myregister = new Register(this);
    this->myregister->setWindowFlag(Qt::Window);
    this->staff_all_info = new SelectStaff(this);
    this->staff_all_info->setWindowFlag(Qt::Window);
    this->staff_all_info->hide();
}


void Widget::on_login_btn_clicked()
{
    if(this->ui->account_line->text().isEmpty())
    {
        QString error_str = "account is empty!";
        QMessageBox::critical(this, "error", error_str);
        return;
    }
    else if(this->ui->password_line->text().isEmpty())
    {
        QString error_str = "password is empty!";
        QMessageBox::critical(this,"error",error_str);
    }
    if(this->ui->root_check->isChecked()) //管理员登录
    {
        char send_info[512] = {0};
        QByteArray usrname = this->ui->account_line->text().toUtf8();
        QByteArray password = this->ui->password_line->text().toUtf8();
        trans_usrinfo_t myinfo;
        sprintf(send_info,"%d",managerlogin_protocol);
        strcpy(myinfo.name,"无");
        strcpy(myinfo.usrname,usrname.data());
        strcpy(myinfo.password,password.data());
        memcpy(send_info + 2,&myinfo,sizeof(myinfo));
        this->socket->write(send_info,sizeof(send_info));
    }
    else //普通用户登录
    {
        char send_info[512] = {0};
        QByteArray usrname = this->ui->account_line->text().toUtf8();
        QByteArray password = this->ui->password_line->text().toUtf8();
        trans_usrinfo_t myinfo;
        sprintf(send_info,"%d",hrlogin_protocol);
        strcpy(myinfo.name,"无");
        strcpy(myinfo.usrname,usrname.data());
        strcpy(myinfo.password,password.data());
        memcpy(send_info + 2,&myinfo,sizeof(myinfo));
        this->socket->write(send_info,sizeof(send_info));
    }
}

void Widget::on_quit_btn_clicked()
{
    this->close();
}

void Widget::on_connect_btn_clicked()
{
    QFile file(("config"));
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "Failed to open file:" << file.errorString();
        this->close();
    }
    char buf[64] = {0};
    char ip_port[2][32];
    memset(ip_port,0,sizeof(ip_port));
    int j;
    bool flag = false;
    int t = 0;
    while(!file.atEnd())
    {
        int len = file.readLine(buf,64);
        for(int i = 0,j = 0,flag = false; i < len;i++)
        {
            if (!buf[i])
            {
             break;
            }
            if (buf[i] == '{')
            {
             flag = true;
             i++;
            }
            else if (buf[i] == '}')
            {
             flag = false;
             ip_port[t][j] = 0;
            }
            if(flag)
            {
                ip_port[t][j++] = buf[i];
            }
        }
        t++;

    }

    QString ip = ip_port[0];
    quint16 port = QString(ip_port[1]).toUShort();
    socket->connectToHost(ip,port);
    file.close();
}
